package cn.myjerry.pattern.singleton;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 测试反射或反序列化破解单例模式
 * @author Jerry
 *
 */
public class Client {
	public static void main(String[] args) throws Exception {
		SingletonDemo04 s1 = SingletonDemo04.getInstance();
		SingletonDemo04 s2 = SingletonDemo04.getInstance();

		System.out.println(s1.hashCode());
		System.out.println(s2.hashCode());
		
		// 通过反射
//		Class<SingletonDemo04> clazz = (Class<SingletonDemo04>) Class.forName("cn.myjerry.pattern.singleton.SingletonDemo04");
//		Constructor<SingletonDemo04> c = clazz.getDeclaredConstructor(null);
//		c.setAccessible(true);
//
//		SingletonDemo04 s3 = c.newInstance(null);
//		SingletonDemo04 s4 = c.newInstance(null);
//		
//		System.out.println(s3.hashCode());
//		System.out.println(s4.hashCode());
		
		// 反序列化
		FileOutputStream fos = new FileOutputStream("/Users/zpon/Desktop/a.txt");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(s1);
		oos.close();
		fos.close();
		
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/zpon/Desktop/a.txt"));
		SingletonDemo04 s5 = (SingletonDemo04) ois.readObject();
		System.out.println(s5.hashCode());
		
	}
}
